package thomas.bier.server;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;

import thomas.bier.shared.Bier;
import thomas.bier.shared.Commentaar;

public class BeerJPAImpl implements BeerJPA {
	@Override
	public boolean addBier(Bier b) {
		EntityManager em = PersistenceManager.get().createEntityManager();
		try{
			em.persist(b);			
		}
		catch(PersistenceException e){
			System.out.println("Error in addBier: "+e.toString());
			return false;			
		}
		finally {
			em.close();
		}
		return true;	
	}

	@Override
	public boolean addCommentaar(Commentaar c, Long bierId) {
		EntityManager em = PersistenceManager.get().createEntityManager();
		Bier b = em.getReference(Bier.class, bierId);
		if(b == null){
			return false;
		}
		else{
			List<Commentaar> commentList = new ArrayList<Commentaar>();
			commentList = b.getCommentaarList();
			commentList.add(c);
			b.setCommentaarList(commentList);
			try{
				em.persist(b);			
			}
			catch(PersistenceException e){
				System.out.println("Error in addBier: "+e.toString());
				return false;			
			}			
		}
		return true;
	}
}
